const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https'),
      body = require('koa-bodyparser'),
      hq = require('./shoppage.js'),
      gohttp = require('gohttp'),
      request = require('request'),
      check = require('./img_check.js');
      up = require('./uploadConfig.js')
const express = require('express');

const options = {
    key:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'./fourgoldhua.cn.crt'))
}
app.use(body());
app.use(cors({
    origin: function (ctx) {
        if (ctx.url === '/test') {
          return "*"; // 允许来自所有域名请求
        }
        return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了 
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

function time(date){
    t1=date;
    t2=new Date().getTime();
    t = t2 -t1;
    //console.log(t);
    if(t<60*1000) return '刚刚';
    else if(t<3600*1000){ 
        t=(t-t%60000)/60000;
        return t+'分钟前';
    }
    else if(t<24*3600*1000){
        t=(t-t%3600000)/3600000;
        return t+'小时前';
    }
    else if(t<365*24*3600*1000){
        t=(t-t%86400000)/86400000;
        return t+'天前';
    }
    else if(t>365*24*3600*1000){
        t=(t-t%31536000000)/31536000000;
        return t+'年前';
    }
}
//修改文字信息
router.get('/shoppage/change',async (ctx)=>{
  let {open_id,field,content} =ctx.request.query;
  log(open_id,field,content)
  hq.update_change(open_id,field,content);
  let arr = await hq.get_openid(open_id);
  //log(arr)
  ctx.body = JSON.stringify(arr)
})
//模糊搜索
router.get('/shoppage/name',async (ctx)=>{
  let { name } =  ctx.request.query;
  let arr = await hq.get_name(name);
  log(arr)
  ctx.body = JSON.stringify(arr);
})

router.get('/shoppage/hot',async (ctx)=>{
  let { id } = ctx.request.query;
  let arr = await hq.get_main(id);
  log(arr)
  ctx.body = JSON.stringify(arr)
})
router.get('/shoppage/del',async (ctx)=>{
  let { open_id } = ctx.request.query;
  await hq.del_shop(open_id);
  let arr = await hq.get_openid(open_id);
  ctx.body = JSON.stringify(arr.length)
})
//商家分享
router.get('/shoppage/select',async (ctx)=>{
 // let {open_id} = ctx.request.query;
  let open_id = ctx.request.header.token;
  let arr = await hq.get_openid(open_id);
  let img0 = await hq.get_img(open_id,0);
  let img1 = await hq.get_img(open_id,1);
  let img2 = await hq.get_img(open_id,2);
  let img3 = await hq.get_img(open_id,3);
  let obj =new Object;
  obj.data = arr;
  obj.image0 = img0;
  obj.image1 = img1;
  obj.image2 = img2;
  obj.image3 = img3;
  log(obj)
  ctx.body = JSON.stringify(obj);
})
//用户拉取数据
router.get('/shoppage/yonghu',async (ctx)=>{
  let { id } = ctx.request.query;
  let arr = await hq.get_id(id);
  let img0 = await hq.get_img(arr[0].open_id,0);
  let img1 = await hq.get_img(arr[0].open_id,1);
  let img2 = await hq.get_img(arr[0].open_id,2);
  let img3 = await hq.get_img(arr[0].open_id,3);
  let obj =new Object;
  obj.data = arr;
  obj.image0 = img0;
  obj.image1 = img1;
  obj.image2 = img2;
  obj.image3 = img3;
  log(obj)
  ctx.body = JSON.stringify(obj);
})
//删除图片
router.post('/shoppage/del',async (ctx)=>{
  let { zl,img } = ctx.request.body;
  let open_id = ctx.request.header.token;
  await hq.del_img(open_id,zl,img);
  let arr = await hq.get_img1(img);
  log(arr.length)
  ctx.body = JSON.stringify(arr.length);
})

//图片检查
const multiparty = require('koa2-multiparty');
router.post('/shoppage/imgcheck', multiparty(), async (ctx) =>{
  //console.log(ctx.req.files);
  const { files } = ctx.req;
  const stream = fs.createReadStream(files.file.path)
  const accesstoken = await check.getAccessToken() 
  const checkResult = await check.imgSecCheck(accesstoken, stream)
  const jsonResult = JSON.parse(checkResult)
  //console.log(jsonResult);
  if (jsonResult.errcode !== 0) {
    ctx.body = JSON.stringify('图片违规');
  } else {
    ctx.body = JSON.stringify('成功');
  }
})
//图片上传
router.post('/shoppage/upload', up.upload.single('file'), async (ctx, next) => {
  const filename1 = '/public/upload/'+ctx.req.file.filename
  const open_id = ctx.request.header.token;
  const zl = ctx.request.header.id;
  hq.insert_img(open_id,zl,filename1);
  ctx.body = filename1; 
});

process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

app.use(router.routes())
   .use(router.allowedMethods());
//app.listen(2227);


https.createServer(options,app.callback()).listen(2333);

